package com.lily.user.domain;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lily.user.infrastructure.common.ObjectConvert;
import com.lily.user.infrastructure.persistent.entity.User;
import com.lily.user.infrastructure.persistent.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserDomain extends UserDM implements UserDomainService{

    @Autowired
    IUserService userService;
    @Override
    public List<UserDM> getAll(UserDM userDM) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(ObjectConvert.convert(userDM,User.class));
//        queryWrapper.eq("name","西施");
        List<User> userList = userService.list(queryWrapper);
        List<UserDM> domainList = new ArrayList<>();

        userList.forEach(obj -> {
            domainList.add(ObjectConvert.convert(obj,UserDM.class));
        });
        return domainList;
    }

    @Override
    public UserDM add(UserDM userDM) {
        User user =  ObjectConvert.convert(userDM, User.class);
        userService.save(user);
        return userDM;
    }

    @Override
    public List<UserDM> page(UserDM userDM, Integer current, Integer size) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(ObjectConvert.convert(userDM,User.class));
//        queryWrapper.eq("name","西施");
        Page<User> page = new Page<>(current,size);
//        Page<User> p = userService.page(page,queryWrapper);
        List<User> userList = userService.page(page,queryWrapper).getRecords();
        List<UserDM> domainList = new ArrayList<>();
        userList.forEach(obj -> {
            domainList.add(ObjectConvert.convert(obj,UserDM.class));
        });
        return domainList;
    }

    @Override
    public UserDM queryOne(UserDM userDM) {
        User user = ObjectConvert.convert(userDM,User.class);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
        User res = userService.getOne(queryWrapper);
        return ObjectConvert.convert(res, UserDM.class);
    }

    @Override
    public UserDM update(UserDM userDM) {
        User user =  ObjectConvert.convert(userDM, User.class);
        userService.updateById(user);
        return userDM;
    }

    @Override
    public UserDM delete(UserDM userDM) {
        User user =  ObjectConvert.convert(userDM, User.class);
        userService.removeById(user);
        return userDM;
    }

}
